package com.jiawa.wiki.exception;

import com.jiawa.wiki.resp.CommonResp;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(BindException.class)
    public CommonResp handlerBindException(BindException exception) {
        return handlerNotValidException(exception);
    }

    /**
     * 对方法参数校验异常处理方法(前端提交的方式为json格式出现异常时会被该异常类处理)
     * json格式提交时，spring会采用json数据的数据转换器进行处理（进行参数校验时错误是抛出MethodArgumentNotValidException异常）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResp handlerArgumentNotValidException(MethodArgumentNotValidException exception) {
        return handlerNotValidException(exception);
    }


    @ExceptionHandler(BusinessException.class)
    public CommonResp handlerBusinessException(BusinessException exception) {
        CommonResp resp = new CommonResp<>();
        resp.setSuccess(false);
        resp.setMessage(exception.getMessage() );
        return resp;
    }

    public CommonResp handlerNotValidException(Exception e) {
        BindingResult result;
        if (e instanceof BindException) {
            BindException exception = (BindException) e;
            result = exception.getBindingResult();
        } else {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            result = exception.getBindingResult();
        }
        StringBuffer errors = new StringBuffer();
        String message = "";
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(error -> {
                System.out.println(error.getDefaultMessage());
                errors.append(error.getDefaultMessage());
            });
            message = fieldErrors.get(0).getDefaultMessage().toString();
        }

        CommonResp resp = new CommonResp<>();
        resp.setSuccess(false);
        resp.setMessage(message );
        return resp;

    }



}
